var express = require('express');
var router = express.Router();
var axios = require('axios');
var cheerio = require('cheerio')
var Promise = require('bluebird');
let hentai = require('../models/hentaiImg')

router.get('/list', (req, res, next) => {
  hentai.getAll('*', (data) =>{
    next(data)
  })
})

router.get('/',function (req, res) {
  let url = req.query.url
  var urlArray = url.split('/')
  let pageNumber = urlArray.pop().split('.')[0]
  let headUrl    = urlArray.join('/')
  console.log(pageNumber)
  console.log(headUrl)
  new Promise((resolve, reject) => {
    try{
      _getUrls({headUrl: headUrl, pageNumber: pageNumber}, 0)
      resolve('执行获取中')
    }catch(e){
      reject(e)
    }

  })
  .then(data =>{
    res.json({
      data: data
    })
  })
  .catch(err => {
    res.json({
      data: 'url出现问题',
      errMessage: err
    })
  })

})

/*
  @param urlData  { headUrl, pageNumber }
 */
function _getUrls(urlData, number, urls){
  let getUrl = ''
  if(number == 1)
    number = 2
  if(number != 0){
    getUrl = urlData.headUrl + '/' + urlData.pageNumber + '_' + number + '.html'
  }else{
    getUrl = urlData.headUrl + '/' + urlData.pageNumber  + '.html'
  }
  console.log(getUrl)/**/
  axios.get(getUrl)
    .then(function(axiosRes){
      if (axiosRes.headers['content-location'].indexOf("404.html") > 0 ){
        console.log('return data')
        return urls
      }else{
        let $ = cheerio.load(axiosRes.data)
        console.log('next data')
        urls.push($('#imgshow > img').attr('src'))
        return _getUrls(urlData, number + 1, urls)
      }
    })
    .catch(function (error){
      return error
    })
}

module.exports = router